import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart.js'
const cart = {
  namespaced: true,
  state: {
    cartList: []
  },
  mutations: {
    // 设置购物车列表
    setCartList (state, payload) {
      state.cartList = payload
    },
    // 单选改变商品选中状态
    setSelected (state, { skuId, selected }) {
      const i = state.cartList.find(item => item.skuId === skuId)
      i.selected = selected
    }
  },
  actions: {
    // 加入购物车 获取购物车列表
    async addCarList ({ commit }, { skuId, count }) {
      // 加入购物车
      await insertCart({ skuId, count })
      // 获取购物车列表
      const { data: { result } } = await findCartList()
      commit('setCartList', result)
    },
    // 删除商品
    async delGoods ({ commit }, ids) {
      // 调用删除接口
      await deleteCart(ids)
      // 删除后重新获取购物车数据
      const { data: { result } } = await findCartList()
      commit('setCartList', result)
    },
    // 改变商品选中状态--单选
    async updateSelected ({ commit }, goods) {
      await updateCart(goods)
      // 修改后重新获取购物车数据
      const { data: { result } } = await findCartList()
      commit('setCartList', result)
    },
    // 全选与反选
    async isAll (context, selected) {
      // 改变全选与全不选状态
      await checkAllCart({
        selected,
        ids: context.state.cartList.map(item => item.skuId)// 将所有商品skuid传送
      })
      // 修改后重新获取购物车数据
      const { data: { result } } = await findCartList()
      context.commit('setCartList', result)
    }
  },
  getters: {
    // 商品总数
    allCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // 商品总价 = 总数 * 价格
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 已选商品数量
    selectedCount (state) {
      // 已选择几件 selected 如果为true就是选中的项
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    },
    // 已选商品合计
    seletedPrice (state) {
      // 所有的列表中seleted为true的项过滤出来 然后把price * count 叠加
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    },
    // 小选影响全选
    checkAll (state) {
      return state.cartList.every(item => item.selected === true)
    }
  }
}

export default cart
